/*
 *
 * Copyright (c) 2023 - future
 * @author fzh
 * @email e_341877120_mail@163.com
 * @link https://mvnrepository.com/search?q=io.github.xrfzh.cn
 *
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package cn.xrfzh.biz.videoViews.service.impl;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import cn.xrfzh.common.utils.XrPageUtil;
import cn.xrfzh.common.redis.RedisCacheClient;
import cn.xrfzh.common.redis.annotation.ClearRedisCache;
import cn.xrfzh.common.utils.XrObjectUtil;
import cn.xrfzh.common.axios.AxiosEnum;
import cn.xrfzh.common.axios.AxiosResult;
import cn.xrfzh.common.exception.MyCustomException;
import cn.xrfzh.common.utils.ParallelStreamUtil;
import cn.xrfzh.biz.videoViews.mapper.VideoViewsMapper;
import cn.xrfzh.api.videoViews.pojo.VideoViews;
import cn.xrfzh.api.videoViews.dto.VideoViewsDto;
import cn.xrfzh.biz.videoViews.service.IVideoViewsService;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 用于存储视频的观看次数，以便跟踪热门视频
 *
 * @author fzh
 * @email e_341877120_mail@163.com
 * @date 2023-10-24 08:36:27
 */
@Service
@Transactional
public class VideoViewsServiceImpl extends ServiceImpl<VideoViewsMapper, VideoViews> implements IVideoViewsService {

    @Resource
    private RedisCacheClient redisCacheClient;

    /**
     * 根据条件查询列表
     *
     * @param videoViewsDto
     * @return
     */
    @Override
    public AxiosResult selectList(VideoViewsDto videoViewsDto) {
        LambdaQueryWrapper<VideoViews> lqw;
        if (XrObjectUtil.checkOfAllNull(videoViewsDto)) {
            lqw = null;
        } else {
            lqw = new LambdaQueryWrapper<>();
        }
        List<VideoViews> videoViewsList = redisCacheClient.queryAllFromRedisIfExists("videoViews", 1800L,
                TimeUnit.SECONDS, VideoViews.class, lqw, this::list);
        boolean flag = ObjectUtils.isNotEmpty(videoViewsList);
        return flag ? AxiosResult.selectSuccess(videoViewsList) : AxiosResult.selectError();
    }

    /**
     * 根据条件分页查询
     *
     * @param currentPage
     * @param pageSize
     * @param videoViewsDto
     * @return
     */
    @Override
    public AxiosResult selectPage(int currentPage, int pageSize, VideoViewsDto videoViewsDto) {
        LambdaQueryWrapper<VideoViews> lqw;
        if (XrObjectUtil.checkOfAllNull(videoViewsDto)) {
            lqw = null;
        } else {
            lqw = new LambdaQueryWrapper<>();
        }
        XrPageUtil xrPageUtil = redisCacheClient.queryByPageFromRedisIfExists("videoViews", 1800L, TimeUnit.SECONDS,
                currentPage, pageSize, lqw, this::list);
        boolean flag = ObjectUtils.isNotEmpty(xrPageUtil);
        return flag ? AxiosResult.selectSuccess(xrPageUtil) : AxiosResult.selectError();
    }

    /**
    * 根据id查询单个
    *
    * @param id
    * @return
    */
    @Override
    public AxiosResult selectOneById(Long id) {
        if (ObjectUtils.isNotEmpty(id)) {
            VideoViews videoViews = getById(id);
            boolean flag = ObjectUtils.isNotEmpty(videoViews);
            return flag ? AxiosResult.selectSuccess(videoViews) : AxiosResult.selectError();
        }
        throw new MyCustomException(AxiosEnum.PARAMETER_ERROR);
    }

    /**
     * 新增
     *
     * @param videoViewsDto
     * @return
     */
    @ClearRedisCache("videoViews")
    @Override
    public AxiosResult insert(VideoViewsDto videoViewsDto) {
        if (ObjectUtils.isNotEmpty(videoViewsDto)) {
            boolean flag = save(videoViewsDto);
            return flag ? AxiosResult.insertSuccess() : AxiosResult.insertError();
        }
        throw new MyCustomException(AxiosEnum.PARAMETER_ERROR);
    }

    /**
     * 更新
     *
     * @param videoViewsDto
     * @return
     */
    @ClearRedisCache("videoViews")
    @Override
    public AxiosResult update(VideoViewsDto videoViewsDto) {
        if (ObjectUtils.isNotEmpty(videoViewsDto)) {
            boolean flag = updateById(videoViewsDto);
            return flag ? AxiosResult.updateSuccess() : AxiosResult.updateError();
        }
        throw new MyCustomException(AxiosEnum.PARAMETER_ERROR);
    }

    /**
    * 根据id删除单个
    *
    * @param id
    * @return
    */
    @ClearRedisCache("videoViews")
    @Override
    public AxiosResult delete(Long id) {
        if (ObjectUtils.isNotEmpty(id)) {
            boolean flag = removeById(id);
            return flag ? AxiosResult.deleteSuccess() : AxiosResult.deleteError();
        }
        throw new MyCustomException(AxiosEnum.PARAMETER_ERROR);
    }

    /**
    * 根据id集合批量删除
    *
    * @param idList
    * @return
    */
    @ClearRedisCache("videoViews")
    @Override
    public AxiosResult deleteBatch(List<Long> idList) {
        if (ObjectUtils.isEmpty(idList) || idList.size() == 0) {
            throw new MyCustomException(AxiosEnum.PARAMETER_ERROR);
        }
        boolean flag = removeByIds(idList);
        return flag ? AxiosResult.deleteSuccess() : AxiosResult.deleteError();
    }

    /**
    * 导入文件
    *
    * @param file
    * @return
    */
    @ClearRedisCache("videoViews")
    @Override
    public AxiosResult importFile(MultipartFile file) {
        boolean flag = false;
        try {
            InputStream inputStream = file.getInputStream();
            ExcelReader er = ExcelUtil.getReader(inputStream);
            List<VideoViews> videoViewsList = er.readAll(VideoViews. class);
            flag = ParallelStreamUtil.insertBatchOfLarge(videoViewsList, baseMapper::insertBatch);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag ? AxiosResult.success(AxiosEnum.IMPORT_SUCCESS) : AxiosResult.error(AxiosEnum.IMPORT_ERROR);
    }

    /**
    * 导出文件
    *
    * @param response
    */
    @Override
    public void exportFile(HttpServletResponse response) {
        try {
            List<VideoViews> videoViewsList = list();
            ExcelWriter ew = ExcelUtil.getWriter(true);
            ew.setOnlyAlias(true);
            ew.write(videoViewsList);
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            String fileName = URLEncoder.encode("Excel导出表", "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
            ServletOutputStream sos = response.getOutputStream();
            ew.flush(sos, true);
            sos.close();
            IoUtil.close(sos);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
